﻿/*
HttpClientManager.Post("http://localhost:60146/Home/Index", new Dictionary<string, string>
{
    { "OrderId", "1" },
    { "PayOrderNumber", "123456" },
});
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace Zo.Http
{
    /// <summary>
    ///
    /// </summary>
    /// <summary>
    ///
    /// </summary>
    public class HttpClientManager
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static string Get(string url, string cookie = "")
        {
            string strHtmlContent;
            HttpWebRequest request;
            try
            {
                //声明一个HttpWebRequest请求
                request = (HttpWebRequest)WebRequest.Create(url);
                //连接超时时间
                request.Timeout = 20000;
                //request.Headers.Set("Pragma", "no-cache");
                //request.AllowAutoRedirect = true;
                //request.MaximumAutomaticRedirections = 3;
                //request.UserAgent = "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 6 Build/MMB29X; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/44.0.2403.119 Mobile Safari/537.36 InFashion/2.9.97";
                request.KeepAlive = true;
                request.Proxy = null;

                if (string.IsNullOrWhiteSpace(cookie))
                {
                    request.Headers.Add("Cookie", cookie);
                }

                var response = (HttpWebResponse)request.GetResponse();
                var streamHtmlCode = response.GetResponseStream();
                if (streamHtmlCode != null)
                {
                    var encoding = Encoding.GetEncoding("utf-8");
                    var streamReader = new StreamReader(streamHtmlCode, encoding);
                    strHtmlContent = streamReader.ReadToEnd();
                    streamReader.Close();
                    streamHtmlCode.Close();
                }
                else
                {
                    strHtmlContent = "请求错误：response.GetResponseStream() 返回的数据是 Null";
                }

                response.Close();
                request.Abort();

                response = null;
            }
            catch (Exception ex)
            {
                return $"请求错误：{ex.Message}";
            }
            finally
            {
                request = null;
            }

            return strHtmlContent ?? string.Empty;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static string Post(string url, IDictionary<string, string> parameters = null)
        {
            var postData = string.Empty;

            if (parameters != null && parameters.Count > 0)
            {
                foreach (var parameter in parameters)
                {
                    if (!string.IsNullOrWhiteSpace(postData))
                    {
                        postData += "&";
                    }

                    var value = HttpUtility.UrlEncode(parameter.Value);
                    //var value = parameter.Value;

                    postData += $"{parameter.Key}={value}";
                }
            }

            var result = OnPost(url, postData);

            return result;
        }

        private static string OnPost(string url, string postData = "", string cookie = "")
        {
            var strHtmlContent = "";
            HttpWebRequest request;
            try
            {
                //声明一个HttpWebRequest请求
                request = (HttpWebRequest)WebRequest.Create(url);
                //连接超时时间
                request.Timeout = 20000;
                //request.Headers.Set("Pragma", "no-cache");
                //request.AllowAutoRedirect = true;
                //request.MaximumAutomaticRedirections = 3;
                //request.UserAgent = "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 6 Build/MMB29X; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/44.0.2403.119 Mobile Safari/537.36 InFashion/2.9.97";
                request.KeepAlive = true;
                request.Proxy = null;

                if (string.IsNullOrWhiteSpace(cookie))
                {
                    request.Headers.Add("Cookie", cookie);
                }

                var data = Encoding.ASCII.GetBytes(postData);

                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;

                using (var stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                var response = (HttpWebResponse)request.GetResponse();
                var streamHtmlCode = response.GetResponseStream();
                if (streamHtmlCode != null)
                {
                    var encoding = Encoding.GetEncoding("utf-8");
                    var streamReader = new StreamReader(streamHtmlCode, encoding);
                    strHtmlContent = streamReader.ReadToEnd();

                    streamReader.Close();
                    streamHtmlCode.Close();
                }
                else
                {
                    strHtmlContent = "请求错误：response.GetResponseStream() 返回的数据是 Null";
                }

                response.Close();
                request.Abort();

                response = null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                request = null;
            }

            return strHtmlContent ?? string.Empty;
        }
    }
}